package com.ykzb.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.ykzb.base.bean.ResultBean;
import com.ykzb.base.constants.TimeConstant;
import com.ykzb.base.exception.BusinessException;
import com.ykzb.base.service.impl.SmsService;
import com.ykzb.constants.Constants;
import com.ykzb.enums.MsgEnumType;
import com.ykzb.enums.SSDBKeys;
import com.ykzb.enums.SysMsgEnumType;
import com.ykzb.redis.RedisClient;
import com.ykzb.user.dao.IUserDao;
import com.ykzb.user.service.UserService;
import com.ykzb.util.RSACoder;
import com.ykzb.util.RSAKey;
import com.ykzb.util.RandomUtil;
import com.ykzb.user.model.User;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@Service
public class UserServiceImpl  implements UserService {

	protected Log log = LogFactory.getLog(this.getClass().getName());

	@Value("${sms.register.signName}")
	private String REGISTER_SIGN_NAME;

	@Value("${sms.register.templateCode}")
	private String REGISTER_TEMPLATE_CODE;

	@Value("${sms.reset.signName}")
	private String RESET_SIGN_NAME;

	@Value("${sms.reset.templateCode}")
	private String RESET_TEMPLATE_CODE;

	@Value("${sms.withdrawals.signName}")
	private String WITHDRAWALS_SIGN_NAME;

	@Value("${sms.withdrawals.templateCode}")
	private String WITHDRAWALS_TEMPLATE_CODE;

	@Value("${sms.boundphone.signName}")
	private String BOUNDPHONE_SIGN_NAME;

	@Value("${sms.boundphone.templateCode}")
	private String BOUNDPHONE_TEMPLATE_CODE;

	@Value("${subject_name}")
	private String SUBJECT_NAME;

	@Autowired
	private RedisClient redisClient;

	@Autowired
	private SmsService smsService;

	@Autowired
	private IUserDao userDao;


	@Override
	public ResultBean login(HttpServletRequest request, String userName, String password) throws Exception{
		ResultBean ret = new ResultBean();
		if (StringUtils.isNotEmpty(userName) && StringUtils.isNotEmpty(password)){
			//模拟APP加密
			String pass = RSACoder.encryptByPublicKey2Base64(RSAKey.REGISTER_PUBLIC_KEY, password);
			//解密
			String pass2 = RSACoder.decryptByPrivateKey4Base64(RSAKey.REGISTER_PRIVATE_KEY, pass);
			User user =  userDao.selectLoginUser(userName,pass2);
			if (user!=null){
				ret.setSuccess(true);
				ret.setData(user);
				request.getSession().setAttribute(Constants.USER_SESSIOON_NAME,user);
			}else{
				ret.setSuccess(false);
			}
		}else{
			ret.setSuccess(false);
		}
        return ret;
	}

	@Override
	public void insert(User user) throws Exception{
		if (user!=null){
			userDao.insert(user);
		}
	}

	/**
	 * 生成手机注册验证码
	 *
	 * @param mobile
	 */
	@Override
	public ResultBean getRegisterCode(String mobile) throws Exception{
		ResultBean ret = new ResultBean();
		if (StringUtils.isEmpty(mobile)){
			ret.setSuccess(false);
		}else{
			if (!StringUtils.isNumeric(mobile)) {
				throw new BusinessException(SysMsgEnumType.PARAM_BLANK);
			}
			// 校验手机号
			boolean mobileExists = userDao.isMobileExists(mobile);
			if (mobileExists) {
				ret.setSuccess(false);
				throw new BusinessException(MsgEnumType.REPEAT_REGISTER_MOBILE);
			}
			// 发送短信
			String randomNum = RandomUtil.randomNum(4);
			redisClient.getJedis().setex(SSDBKeys.mobile_code + mobile, 10 * TimeConstant.ONE_MINUTE_SECOND, randomNum);
			Map<String, String> map = new HashMap<String, String>();
			map.put("code", randomNum);
			map.put("product", SUBJECT_NAME);
			boolean success = smsService.sendNormalSms(REGISTER_SIGN_NAME, REGISTER_TEMPLATE_CODE, mobile, JSON.toJSONString(map));
			if (!success) {
				ret.setSuccess(false);
				throw new BusinessException(MsgEnumType.REGISTER_SMS_ERROR);
			}else{
				ret.setSuccess(true);
			}

		}
		return ret;
	}

	@Override
	public boolean isMobileExists(String mobile) throws Exception {
		if (StringUtils.isEmpty(mobile)){
			return false;
		}else{
			return userDao.isMobileExists(mobile);
		}

	}

	/**
	 * 根据手机号查询密码
	 * @param mobile
	 * @return
	 * @throws Exception
	 */
	@Override
	public User getUserByMobile(String mobile) throws Exception {
		if (StringUtils.isEmpty(mobile)){
			return null;
		}else{
			return userDao.selectUserByMobile(mobile);
		}
	}


//	/**
//	 * 重置密码
//	 *
//	 * @param mobile
//	 * @param p
//	 * @param resetCode
//	 */
//	// TODO
//	public void resetPwd(String mobile, String p, String resetCode) {
//		if (!StringUtils.isNumeric(mobile)) {
//
//		}
//
//		// 校验验证码
//		String correctCode = redisClient.getJedis().get("XXXXXX" + mobile);
//
//
//		return null;
//	}


}